package TController
{
	//import CustomEvents.*;
	
	
	import PComm.TComm;
	
	import PDatabase.TDatabase;
	
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	import br.com.stimuli.loading.loadingtypes.URLItem;
	import br.com.stimuli.loading.loadingtypes.XMLItem;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	import mx.controls.*;
	
	
	
	public class Controller extends flash.events.EventDispatcher
	{

		public var database:TDatabase;
		public var app:Object;
		public var comm:TComm;
		public var loader:BulkLoader;
		
		public var fileList:Array=new Array();
		public var books:Array=new Array();
		public var fileCollection:ArrayCollection=new ArrayCollection();
		public var path:String="";
		[Bindable]
		public var pattern:String="";
		
 		

		public function Controller()
		{
			database=new TDatabase();
			loader=new BulkLoader("main");
			loader.numConnections;
			loader.addEventListener(BulkLoader.ERROR, onBulkError);
			database.openDatabase("books.db");
			/*TBook.prototype.isbn="";
			TBook.prototype.isbn13="";
			TBook.prototype.filename="";
			TBook.prototype.path="";
			TBook.prototype.oldname="";
			TBook.prototype.newname="";
			TBook.prototype.book_id="";
			TBook.prototype.title="";
			TBook.prototype.titleLong="";
			TBook.prototype.authorsText="";
			TBook.prototype.publisherText="";
			TBook.prototype.description="";
			TBook.prototype.publisher="";
			TBook.prototype.detailsPhysical="";
			TBook.prototype.language="";
			TBook.prototype.edition_info="";
			TBook.prototype.subjects="";
			TBook.prototype.summary="";
			TBook.prototype.rawData="";*/
		}
		
		public function getISBNfromFilename(s:String):String
		{
			var isbn:String="";		
			
			var pattern:RegExp = /\d{1,5}\d{1,7}\1\d{1,6}\1(\d|X|x)/gi;
			var result:Array = pattern.exec(s);			
			while (result != null)
			{
    			//trace(result.index, "\t", pattern.lastIndex, "\t", result);
    			isbn=result[0];
    			trace(isbn);
    			result = pattern.exec(s);
			}

			return isbn;
		}
		
		public function showInfo(i:int):void
		{
			var book:TBook=books[i];
			var textarea:TextArea=(app as ISBNLookuper).infoTextArea;
			
			if(book==undefined||book==null)
			{
			 textarea.text="No data";
			 return;  
   			 //newFilenameText.text=makeNewFilename(book);
			}
			
			var newFilenameText:TextInput=(app as ISBNLookuper).newFilenameTextInput
			var s:String="";
			if(book.book_id==undefined){textarea.text=s;;return;};
			
			for(var key:String in book)
			if(key!="rawData")
				{
					s+="\n"+key+": " + book[key];
				}
			/*s+="\nBook id: "+book.book_id;
			s+="\n\nISBN: "+book.isbn;
			s+="\nISBN13: "+book.isbn13;
			s+="\n\nTitle: "+book.title;
			s+="\nTitleLong: "+book.titleLong;
   			s+="\n\nAuthors: "+book.authorsText;
   			*/
   			textarea.text=s;  
   			newFilenameText.text=makeNewFilename(book);
		}
		
		public function getData():void
		{
			for(var i:int=0;i<5;i++)
			{
				var book:TBook=books[i];
				if(book==undefined){book=new TBook();books[i]=book;};
				var isbn:String=getISBNfromFilename(fileList[i]);
				if(isbn.length>9)
					book.isbn13=isbn;
				if(isbn.length==9)
					book.isbn=isbn;
				if(isbn.length<9||isbn.length>13){}
				 else sendISBNrequest(i);
			}
			loader.start();
			/*var book:TBook=new TBook();
			book.rawData="<ISBNdb server_time=\"2009-12-13T12:48:07Z\">\n<BookList total_results=\"1\" page_size=\"10\" page_number=\"1\" shown_results=\"1\">\n<BookData book_id=\"essential_physiological_biochemistry_a01\" isbn=\"0470026367\" isbn13=\"9780470026366\"><Title>Essential Physiological Biochemistry</Title>\n<TitleLong>Essential Physiological Biochemistry: An Organ Systems Based Approach</TitleLong><AuthorsText>Stephen Charles Reed, </AuthorsText><PublisherText publisher_id=\"john_wiley_sons\">John Wiley & Sons</PublisherText><Details change_time=\"2008-08-17T02:42:26Z\" price_time=\"2009-12-12T08:09:40Z\" edition_info=\"Paperback; 2008-09-12\" language=\"\" physical_description_text=\"1.1 lb; 320 pages\" lcc_number=\"\" dewey_decimal_normalized=\"\" dewey_decimal=\"\"/></BookData></BookList></ISBNdb>";
			processXML(book);*/
		}
		
		public function onBulkError(evt:BulkProgressEvent):void
		{
			
		}
		
		public function sendISBNrequest(i:int):void
		{
			//
			var isbnNumber:String="";
			if((books[i] as TBook).isbn13=="")isbnNumber=(books[i] as TBook).isbn;
			 else isbnNumber=(books[i] as TBook).isbn13;
			
			var apikey:String="J2DYCZNZ";
			var value1:String=isbnNumber;
			var url:String="http://isbndb.com/api/books.xml?access_key="+apikey+"&index1=isbn&value1="+value1+"&results=details&results=texts&results=subjects";
			loader.add(url,{id:String(i),priority:0});
			loader.get(String(i)).addEventListener(Event.COMPLETE, onItemDone);
			loader.get(String(i)).addEventListener(BulkLoader.ERROR, onItemError);			
			trace(url);
		}
		
		public function onItemError(evt:ErrorEvent):void
		{
			trace("something went bad");
			var objRaw:Object;
            if(evt.currentTarget is XMLItem==true)
             objRaw=evt.currentTarget as XMLItem
            else 
             objRaw=evt.currentTarget as URLItem;
            var id:String=objRaw.id;
			//var id:String=urlClean((evt.currentTarget as URLItem).id);
			
			trace(id+" went bad");
		}
		
		public function onItemDone(evt:Event):void
		{
            //trace("All items are loaeded and ready to consume");
            var objRaw:Object;
            if(evt.currentTarget is XMLItem==true)
             objRaw=evt.currentTarget as XMLItem
            else 
             objRaw=evt.currentTarget as URLItem;
            var id:String=objRaw.id;
            var obj:TBook=books[id];
            //trace(evt.currentTarget);
            //trace(loader.getContent(urlClean(evt.currentTarget.url),true));
            obj.rawData=loader.getContent(id,true);
            
            //trace(obj.rawData);
            //loader.remove(urlClean(evt.currentTarget.url));
           
             processXML(obj);
            //loader.remove("google");
  		}
  		
  		public function makeNewFilename(book:TBook):String
  		{
  		/*	%b book.book_id
			%d book.description
			%I book.isbn13
			%i book.isbn
			%t book.title
			%T book.titleLong
   			%a book.authorsText
   		*/
   			var newf:String="";
   			
   			for(var i:int=0;i<pattern.length;i++)
   			{
 			
 			if(pattern[i]=="\\"&&i==pattern.length-1)
 				{
 					newf+=pattern[i];
 					continue;	
 				} 				
 				
 			if(pattern[i]=="\\"&&i!=pattern.length-1)
 				if(pattern[i+1]!="%")
 					{
 						newf+=pattern[i];
 						continue; 						
 					}
 				else
 					{
 						newf+="%";
 						i++;
 						continue;
 					}
   			
 			if((pattern[i]=="%"&&i==pattern.length-1)||(pattern[i]!="%"))
 				{
 					newf+=pattern[i];
 					continue;	
 				}
 				
 			 			
 			if(pattern[i]=="%")
 				{
 					if(pattern[i+1]=="b")newf+=book.book_id
 					else if(pattern[i+1]=="d")newf+=book.description;
 					else if(pattern[i+1]=="I")newf+=book.isbn13;
 					else if(pattern[i+1]=="i")newf+=book.isbn;
 					else if(pattern[i+1]=="t")newf+=book.title;
 					else if(pattern[i+1]=="L")newf+=book.titleLong;
 					else if(pattern[i+1]=="a")newf+=book.authorsText;
 					 else newf+="%";
 					continue;
 				}
   			}
 			return newf;
  		}

  		public function processXML(book:TBook):void
  		{
  			var xmlData:XML=new XML(book.rawData);
  			//trace(book.rawData);
  			//if((xmlData.ISBNdb.BookList==undefined)||(xmlData.ISBNdb.BookList==null))return;
  						
			book.book_id=xmlData.BookList.BookData[0].@book_id;
			book.description="";
			book.isbn13=xmlData.BookList.BookData[0].@isbn13;
			book.isbn=xmlData.BookList.BookData[0].@isbn;
			book.title=xmlData.BookList.BookData[0].Title;
			book.titleLong=xmlData.BookList.BookData[0].TitleLong;
   			book.authorsText=xmlData.BookList.BookData[0].AuthorsText;
   			book.publisher=xmlData.BookList.BookData[0].PublisherText;
   			book.detailsPhysical=xmlData.BookList.BookData[0].Details.@physical_description_text;
   			book.language=xmlData.BookList.BookData[0].Details.@language;
   			book.edition_info=xmlData.BookList.BookData[0].Details.@edition_info;
   			for(var i:int=0;i<xmlData.BookList.BookData[0].subjects.length;i++)
   			 book.subjects+=xmlData.BookList.BookData[0].subjects[i]+"\n";
  			book.summary=xmlData.BookList.BookData[0].Summary;
  			trace(book.isbn13,book.isbn,book.title,book.authorsText);
  		}
		
		public function getFilesRecursive(folder:String):void {
            //the current folder object
            var currentFolder = new File(folder);
            
            //the current folder's file listing
            var files = currentFolder.getDirectoryListing();
            
            //iterate and put files in the result and process the sub folders recursively
            for (var f = 0; f < files.length; f++) {
                if (files[f].isDirectory) {
                    if (files[f].name !="." && files[f].name !="..") {
                        //it's a directory
                        getFilesRecursive(files[f].nativePath);
                    }
                } else {
                    //it's a file yupeee
                    fileList.push(files[f].nativePath);
                }
            }            
            
        }
        
            
		
		public function onDirSelected(event:Event):void 
		{
			path=(event.currentTarget as File).nativePath;	
		  	getFilesRecursive(path);
    	  	trace(path);
    	  	//trace(fileList);
    	  	fileCollection=new ArrayCollection(fileList)
    	  	for(var i:int=0;i<fileList.length;i++)
    	  	{
	    	  	fileList[i]=(fileList[i] as String).replace(path+"\\","");
	    	  	
    	  	}
    		(app as ISBNLookuper).filenameList.dataProvider=fileCollection;
    		books=new Array();
    		trace(fileList);
    		
    	}
		
		public function browseForFolder():void
		{
			var file:File = new File(); 
			file.addEventListener(Event.SELECT, onDirSelected); 
			file.browseForDirectory("Select a directory"); 
		}

		public function startAction(evt:MouseEvent):void
		{
			trace("starting something");
			var dbCond:String="";
			var zeTwitter:String="users (id INTEGER PRIMARY KEY, name varchar(255), rank int(11), followers varchar(255), nrfollowers int(11), following varchar(255), nrfollowing int(11), name2 varchar(255), location varchar(255), web varchar(255), image varchar(255), UNIQUE(name))";
			dbCond=zeTwitter;
			database.createDatabase(File.applicationDirectory.resolvePath("tut1.db").nativePath,dbCond);
			
			//trace(DiskReading.getFiles(File.applicationDirectory.resolvePath("Data").nativePath));
    
		}
		
		public function makeObj(xObj:XML):Object 
		{  
     //----- Initialise objects
     var obj:Object=new Object();  
     if (xObj == null) {  
         return null;  
     }  
     if (obj == null) {  
         obj = {};  
     }  
     var a, c, nName, nType, nValue, cCount;  
     //----- Add attributes to the object  
     for (a in xObj.attributes) {  
         obj[a] = xObj.attributes[a]  
     }  
     //----- Build child nodes  
     for (c in xObj.childNodes) {  
         nName = xObj.childNodes[c].nodeName;  
         nType = xObj.childNodes[c].nodeType;  
         nValue = xObj.childNodes[c].nodeValue;  
         if (nType == 3) {  
             obj._value = nValue;  
             obj._type = 'text';  
         }  
         if (nType == 1 && nName != null) {  
             if (obj[nName] == null) {  
                 obj[nName] = makeObj(xObj.childNodes[c]);  
             } else if (obj[nName]._type != 'array') {  
                 obj[nName] = [obj[nName]];  
                 obj[nName]._type = 'array';  
             }  
             if (obj[nName]._type == 'array') {  
                 obj[nName].unshift(makeObj(xObj.childNodes[c]));  
             }  
         }  
     }  
     // Return object  
     return obj;  
 };  
 
		
	}
}